package com.example.a315;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void myclick(View view){
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                //发起请求，读取html代码
                try {
                    final String result = getHtml();

                    //更新界面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            EditText editTextHtml = findViewById(R.id.e2Text2);
                            editTextHtml.setText(result);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }

    private String getHtml()throws Exception{

        final EditText editText = findViewById(R.id.eText);


        //连接地址
        String url = "http://39.99.228.8:8080/news/testapi/query.jsp?PhoneCode=";
        String urlAddress = url + editText.getText();
        URL url1 = new URL(urlAddress);
        //建立连接
        HttpURLConnection connection = (HttpURLConnection)url1.openConnection();
        //得到数据流
        InputStream is = connection.getInputStream();
        //缓存读取，用来读取文本
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
        String result = "";
        while (true){
            String line = bufferedReader.readLine();
            if(line==null){
                break;
            }
            result += line;
        }
        Log.d("test",result);
        is.close();

        return result;
    }
}
